﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using System.IO;
using System.Drawing;
using Bussiness.Service;

namespace Bussiness.View.BackEnd.User_Control
{
    public partial class Image_Product : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Hidden id = (Hidden)this.Parent.FindControl("pu_id");
            
            if (!X.IsAjaxRequest)
            {
                if (id.Value != null )
                loadImage(id.Value.ToString());
            }
        }

        protected void UpLoadFile(object sender, DirectEventArgs args)
        {
            Hidden id = (Hidden)this.Parent.FindControl("pu_id");

            string filename = id.Value.ToString() +"_"+DateTime.Now.ToString("HHmmssddMMyyyy");
            var fileName = string.Format("{0}\\" + filename + ".jpg", Server.MapPath("/Addmin/BackEnd/images/large"));
            var fileNameSmall = string.Format("{0}\\" + filename + ".jpg", Server.MapPath("/Addmin/BackEnd/images/small"));
            pu_FileUpLoad.PostedFile.SaveAs(fileName);

            Bitmap tempBmp = new Bitmap(fileName);
            Bitmap bmp = new Bitmap(tempBmp, 150, 150);

            bmp.Save(fileNameSmall, System.Drawing.Imaging.ImageFormat.Jpeg);
            loadImage(id.Value.ToString());
        }


        public void loadImage(string id)
        {
            string path = Server.MapPath("/Addmin/BackEnd/images/small");
            
            this.Store1.DataSource = new ImageService().loadImage(id,path);
            this.Store1.DataBind();
        }


        protected void deleteImage(object sender, DirectEventArgs e)
        {
            string json = e.ExtraParams["Values"];
            Dictionary<string, string>[] images = JSON.Deserialize<Dictionary<string, string>[]>(json);
            foreach (var value in images)
            {
                foreach (KeyValuePair<string, string> keyValuePair in value)
                {
                    if (keyValuePair.Key.Equals("Url"))
                    {
                      string[] filename = keyValuePair.Value.Split('/');
                        string str = filename[filename.Length-1];
                        File.Delete(Server.MapPath("/Addmin/BackEnd/images/small/" + filename[filename.Length - 1]));
                        File.Delete(Server.MapPath("/Addmin/BackEnd/images/large/" + filename[filename.Length - 1]));
                    }
                }
            }
            Hidden id = (Hidden)this.Parent.FindControl("pu_id");
            loadImage(id.Value.ToString());
        }
    }
}